package org.zhu.back.tencentCloudStorage;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.zhu.back.mysqlBackUp.BackUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by yingzhi zhu on 2017/9/14.
 * TODO 在云端上测试一下
 */
public class Client {

    private static final String FileSeparator = "/";
    private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;

    public static void main(String[] args) throws InterruptedException {
// 1 初始化身份信息
        COSCredentials cred = new BasicCOSCredentials("1252102424", "AKIDFKAk5Bhez5vUmot8VdV8VdWAYKwOmV9b",
                "Vt63kHcjZ1DKMAqJWS7WigPuBE3bs8E4");
// 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-chengdu"));
// 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
// 操作API， 如下文所述.或者参照Demo(https://github.com/tencentyun/cos-java-sdk-v5/blob/master/src/main/java/com/qcloud/cos/demo/Demo.java)
        String bucketName = "yilongfuping";
//        Timer timer = new Timer();
//        timer.scheduleAtFixedRate(new TimerTask() {
//            @Override
//            public void run() {
//
//                try {
//                    String saveDir = FileSeparator+getCurrentName() + FileSeparator;
//                    saveSql(cosClient, bucketName, getCurrentName() + FileSeparator);
//                    saveFiles("C:\\Users\\1\\Desktop\\gif", cosClient, bucketName, saveDir);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("caocaocoa");
//            }
//        }, getDate(), PERIOD_DAY);

    }

    public static void deleteObj(COSClient cosClient, String bucketName) {
        String key = "";

        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, key);
        cosClient.deleteObject(deleteObjectRequest);
    }

    // 2017-09-18 23-59-59 2017-09-19 23-59-59 2017-09-20 23-59-59 2017-09-21 23-59-59 2017-09-22 23-59-59
    public static void getObj(COSClient cosClient, String bucketName, String prefix) {
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(bucketName);
// 设置 delimiter 为/, 即获取的是直接成员，不包含目录下的递归子成员
//        listObjectsRequest.setDelimiter("");
        listObjectsRequest.setPrefix(prefix);
        ObjectListing objectListing = cosClient.listObjects(listObjectsRequest);
        List<COSObjectSummary> objectListSummary = objectListing.getObjectSummaries();
        objectListSummary.forEach((item) -> {
                    System.out.println(item.getKey());
                    DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, item.getKey()
                    );
                    cosClient.deleteObject(deleteObjectRequest);
                }
        );


    }

    public static void saveSql(COSClient cosClient, String bucketName, String dir) throws IOException, InterruptedException {
        BackUtil backUtil = new BackUtil()
                .setMysqlHome("F:\\java\\mysql-5.6.24-win32\\bin\\")
                .setBackCommand("localhost", "root", "olive888", "sanploy_fuping");
        String sqlPath = backUtil.backUp("F:\\", getCurrentName() + ".sql");
        upload(cosClient, new File(sqlPath), bucketName, dir);
    }

    public static void saveFiles(String oldDir, COSClient cosClient, String bucketName, String saveDir) {
        File file = new File(oldDir);
        String dirName = file.getName();
        Optional.ofNullable(file.listFiles()).ifPresent(fileList -> {
            for (File item : fileList) {
                try {
                    upload(cosClient, item, bucketName, saveDir + dirName + FileSeparator);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public static void upload(COSClient cosClient, File localFile, String bucketName, String dir) throws InterruptedException {
        // 上传文件(推荐), 支持根据文件的大小自动选择单文件上传或者分块上传
        // 同时支持同时上传不同的文件
        TransferManager transferManager = new TransferManager(cosClient);
        // transfermanger upload是异步上传
        String key = dir + localFile.getName();
        Upload upload = transferManager.upload(bucketName, key, localFile);
        // 等待传输结束
        upload.waitForCompletion();
        transferManager.shutdownNow();
    }

    public static Date getDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23); //11点
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime(); //第一次执行定时任务的时间
    }

    public static String getCurrentName() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        return formatter.format(currentTime);
    }


}
